<template>
	<headers></headers>
	<notice :notice.sync="notice"></notice>
	<div class="container">
        <div class="row regis-form">
            <div class="col-md-4 col-md-offset-4">
                <div class="panel paenl-default">
                    <div class="panel-body">
                        <div class="form-top">
                            <div class="form-top-left">
                                <h3 class="mytitle">{{state==='teacher'?'教师注册':'学生注册'}}</h3>
                            </div>
                            <div class="form-top-right">
                                <button class="btn btn-link" id="switch-ident" @click="changeState">
                                {{state==='teacher'?'学生注册':'教师注册'}}<span class="glyphicon glyphicon-chevron-right"></span>
                                </button>
                            </div>
                        </div>
                        <div class="form-body">
                        	<validator name="register">
                            <form class="col-md-4" id="register-form" novalidate>
                                <div class="form-group has-feedback" id="email" 
                                    :class="{'has-error': $register.email.dirty&&$register.email.invalid, 'has-success': $register.email.dirty&&$register.email.valid}" >
                                    <input type="email" class="form-control has-feedback" placeholder="请输入邮箱"
                                           required name="email"
                                           v-model="formData.email" detect-change="off"
                                           v-validate:email="formFileds.email.validate">
                                    <span class="help-block" v-if="$register.email.dirty&&$register.email.invalid">
                                    	{{$register.email.errors&&$register.email.errors[0].message}}
                                    </span>
                                    <span class="glyphicon form-control-feedback" v-if="$register.email.dirty" 
                                        :class="{'glyphicon-remove': $register.email.invalid, 'glyphicon-ok': $register.email.valid}"></span>
                                </div>
                                <div class="form-group" id="choose_college" 
                                    :class="{'has-error': $register.school.dirty&&$register.school.invalid, 'has-success': $register.school.dirty&&$register.school.valid}" >
                                    <select class="form-control" v-model="formData.school" v-validate:school="formFileds.school.validate">
                                        <option value="select">选择学校</option>
                                        <option v-for="item in colleges" :value="item.col_id">{{item.col_name}}</option>
                                    </select>
                                    <span class="help-block" v-if="$register.school.dirty&&$register.school.invalid">
                                        {{$register.school.errors&&$register.school.errors[0].message}}
                                    </span>
                                </div>
                                <div class="form-group has-feedback" id="teacher_id" 
                                    :class="{'has-error': $register.number.dirty&&$register.number.invalid, 'has-success': $register.number.dirty&&$register.number.valid}" >
                                    <input type="text" class="form-control" 
                                           :placeholder="'请输入'+(state==='teacher'?'教师证号':'学号')" 
                                           required pattern="^[a-zA-Z0-9]+$" max="10" name="number"
                                           v-model="formData.number" detect-change="off" 
                                           v-validate:number="formFileds.number.validate">
                                    <span class="help-block" v-if="$register.number.dirty&&$register.number.invalid">
                                    	{{$register.number.errors&&$register.number.errors[0].message}}
                                    </span>
                                    <span class="glyphicon form-control-feedback" v-if="$register.number.dirty" 
                                        :class="{'glyphicon-remove': $register.number.invalid, 'glyphicon-ok': $register.number.valid}"></span>
                                </div>
                                <div class="form-group" id="name">
                                    <input type="text" class="form-control" 
                                           placeholder="请输入您的真实姓名" required
                                           v-model="formData.name">
                                </div>
                                <div class="form-group has-feedback" id="password"
                                    :class="{'has-error': $register.psw.dirty&&$register.psw.invalid, 'has-success': $register.psw.dirty&&$register.psw.valid}" >
                                    <input type="password" class="form-control" 
                                           placeholder="请输入您的密码" required
                                           v-model="formData.psw" detect-change="off" initial="off"
                                           v-validate:psw="formFileds.psw.validate">
                                    <span class="help-block" v-if="$register.psw.dirty&&$register.psw.invalid">
                                        {{$register.psw.errors&&$register.psw.errors[0].message}}
                                    </span>
                                    <span class="glyphicon form-control-feedback" v-if="$register.psw.dirty" 
                                        :class="{'glyphicon-remove': $register.psw.invalid, 'glyphicon-ok': $register.psw.valid}"></span>
                                </div>
                                <div class="form-group has-feedback" id="password2"
                                    :class="{'has-error': $register.pswConfirm.dirty&&$register.pswConfirm.invalid, 'has-success': $register.pswConfirm.dirty&&$register.pswConfirm.valid}" >
                                    <input type="password" class="form-control" 
                                           placeholder="确认密码" required
                                           v-model="formData.pswConfirm" detect-change="off"
                                           v-validate:psw-confirm="{
                                                required: {rule: true, message: '请确认密码'},
                                                confirm: {rule: formData.psw, message: '两次输入的密码不一致'}
                                            }">
                                    <span class="help-block" v-if="$register.pswConfirm.dirty&&$register.pswConfirm.invalid">
                                        {{$register.pswConfirm.errors&&$register.pswConfirm.errors[0].message}}
                                    </span>
                                    <span class="glyphicon form-control-feedback" v-if="$register.pswConfirm.dirty" 
                                        :class="{'glyphicon-remove': $register.pswConfirm.invalid, 'glyphicon-ok': $register.pswConfirm.valid}"></span>
                                </div>
                                <input type="submit" id="register" class="btn btn-primary" value="注册" alt="注册" @click="register" :disabled="!$register.valid"/>
                            </form>
                        	</validator>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
	import Headers from '../../Component/Header/Header.vue';
	import Notice from '../../Component/Notice/Notice';

	export default {
        created: function() {
            this.$http.get('/college/college').then(function(resp) {
                    if (resp.data.status === 1) {
                        this.colleges = resp.data.data;
                    }
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
        },
		data() {
			return {
                state: 'teacher',
                formData: {
                    email: "",
                    school: "select",
                    number: "",
                    name: "",
                    psw: "",
                    pswConfirm: "",
                },
                colleges: [],
                notice: {type: 0, msg: ""},
                formFileds: {
                    email: {
                        validate: {
                            required: {rule: true, message: '请输入邮箱'},
                            email: {rule: true, massage: ''},
                            emailExist: {rule: true, initial: 'off'}
                        }
                    },
                    school: {
                        validate: ['selSchool']
                    },
                    number: {
                        validate: {
                            required: {rule: true, message: '请输入学号'},
                            maxlength: {rule: 20, message: '不能超过20位'},
                            minlength: {rule: 4, message: '不能少于4位'},
                            idRule: {rule: true, message: '只能是数字或字母'},
                            numberExits: {rule: true, initial: 'off'},
                            selSchool: {rule: true, message: '请先选择学校'},
                        }
                    },
                    psw: {
                        validate: {
                            minlength: {rule: 6, message: '不能少于6位'},
                            required: {rule: true, message: '请输入密码'}
                        }
                    }
                }
			}
		},
		methods: {
			register: function(e) {
				e.preventDefault();
                var postUrl = this.state === 'teacher'? '/Teacher/add' : '/Student/add',
                    postData = this.state === 'teacher'? {
                        tea_email: this.formData.email, col_id: this.formData.school,
                        tea_number:this.formData.number,tea_name: this.formData.name,tea_password_hash: this.formData.psw
                    } : {
                        stu_email: this.formData.email, col_id: this.formData.school,
                        stu_number:this.formData.number, stu_name: this.formData.name, stu_password_hash: this.formData.psw
                    };
                console.log(postData);
                this.$http.post(postUrl, postData).then(function(resp) {
                    if (resp.data.status === 1) {
                        this.notice = {type: 1, msg: '注册成功'};
                        setTimeout(function() {
                            window.location.href = "/Account/login.html";
                        }, 1000)
                    } else {
                        this.notice = {type: 0, msg: resp.data.message};
                    }
                    
                    
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
			},
            changeState: function() {
                this.state = this.state === 'teacher' ? 'student' : 'teacher';
                this.formData = {
                    email: "",
                    school: "select",
                    number: "",
                    name: "",
                    psw: "",
                    pswConfirm: "",
                }
                this.$resetValidation();
            }
		},
		components: {
			Headers,
			Notice
		},
		validators: {
            email: {
                message: '请输入正确的邮箱地址',
                check: function (val) {
                    return /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(val)
                  }
            },
            selSchool: { // 验证确保选择学校
                message: '请选择学校',
                check: function (val) {
                    if (this.field === 'number') {
                        val = this.vm.formData.school;
                        if (val === 'select')
                            this.vm.formData.number = '';
                    }
                    return val != 'select';
                }
            },
            idRule: function(val) {
                return /^[a-zA-Z0-9]+$/.test(val)
            },
            confirm: function(val, target) {
                return val === target;
            },
            emailExist (val) {
                return this.vm.$http.post('/index/check_email', {
                    email: val
                }).then((res) => { // done
                    return res.data;
                }).then((data) => {
                    if (data.status === 1)
                       return Promise.resolve();
                    else {
                       return Promise.reject(data.message)
                    }
                }).catch((error) => {
                    return Promise.reject(error)
                })
            },
            numberExits (val) {
                if (this.vm.formData.school === 'select') return true;
                var postUrl = this.vm.state === 'teacher'? '/teacher/check_number' : '/student/check_number',
                    postData = this.vm.state === 'teacher'? 
                    {tea_number: this.vm.formData.number, col_id: this.vm.formData.school} : 
                    {stu_number: this.vm.formData.number, col_id: this.vm.formData.school};
                return this.vm.$http.post(postUrl, postData
                ).then((res) => { // done
                    return res.data;
                }).then((data) => {
                    if (data.status === 1)
                       return Promise.resolve();
                    else {
                       return Promise.reject(data.message)
                    }
                }).catch((error) => {
                    return Promise.reject(error)
                })
            }
        }
	}
</script>

<style>
.regis-form {
	margin-top: 80px;
}

.form-top {
	overflow: hidden;
	padding: 0px 15px;
}
.form-top-left {
	float: left;
}

.form-top-left h3{
	margin-top: 10px;
	float: left;
}

.form-top-right {
	margin-top: 10px;
	float: right;
}

.form-top-right button.btn{
	color: #818181;
}

.form-top-right button.btn:focus{
	outline: 0;
	text-decoration: none;
}

.form-top-right button.btn:hover{
	opacity: 0.6;
	text-decoration: none;
}

.form-body {
	overflow: hidden;
	padding: 10px 0px;
}

.form-body form{
	width: 100%;
}

.form-body .btn{
	width: 100%;
}

.form-body .form-group {
	margin-bottom: 18px;
}

.alert-danger {
	top: 60px;
}
</style>